const tableConfig = require('../../config/mongodbTable'); // 引入表配置
const XLSX = require('xlsx'); // 添加对 xlsx 库的引用
const moment = require('moment');
const fs = require('fs');
const path = require('path');

class MongodbDataInit {
    constructor(db) {
        this.mongodbServer = db;
    }   
    async init() {

        await this.ensureStoreCollectionExists(); // 初始化数据库
        // await this.insertStoreData(); // 调用插入店家数据的方法
        // await this.insertFoodData(); // 调用插入食物营养数据的方法
    }

    /**
     * 确保集合存在，如果不存在则创建
     */
    async ensureStoreCollectionExists() {
        const collections = await this.mongodbServer.listCollections();
        const collectionNames = collections.map(collection => collection);

        for (const [collectionName, config] of Object.entries(tableConfig)) {
            if (!collectionNames.includes(collectionName)) {
                await this.mongodbServer.createCollection(collectionName, {
                    validator: {
                        $jsonSchema: {
                            required: config.required, // 使用表配置中的必填字段
                            properties: config.properties, // 使用表配置中的属性定义
                        } // 使用表配置中的 JSON 模式
                    }
                });

                // 创建索引
                for (const index of config.indexes) { // 使用表配置中的索引定义
                    await this.mongodbServer.createIndex(collectionName, index.key, index.options);
                }
            }
        }
    }

    /**
     * 插入模拟数据
     */
    async insertStoreData() {
        const workbook = XLSX.readFile('data/huizhoumeishi.xlsx');
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const data = XLSX.utils.sheet_to_json(worksheet);

        const foodFilePath = path.join(__dirname, '../../data/food.json');
        let foodData = {};
        if (fs.existsSync(foodFilePath)) {
            foodData = JSON.parse(fs.readFileSync(foodFilePath, 'utf8'));
        }
        // 数据转换
        const transformedData = data
            .filter(item => item.recommendedDishes && item.businessStatus !== '暂停营业') // 过滤数据
            .map(item => {
                // 遍历 recommendedDishes 数组并添加到 foodData 中
                item.recommendedDishes = item.recommendedDishes.split(' ');
                item.recommendedDishes.forEach((dish, index) => {
                    if (!foodData[dish]) {
                        foodData[dish] = {
                            "name": dish,
                            "description": ""
                        };
                    }
                });
                return {
                    openid: "dzdp" + item.openid, // 确保 openid 是字符串
                    platform: "zddp",
                    merchant: item.merchant,
                    cityCode: item.cityCode,
                    province: item.province,
                    city: item.city,
                    district: item.district,
                    location: {
                        type: 'Point',
                        coordinates: [parseFloat(item.longitude), parseFloat(item.latitude)] // 将经纬度转换为浮点数
                    },
                    reviewCount: parseInt(item.reviewCount, 10), // 将评论数转换为整数
                    averageCost: item.averageCost ? parseInt(item.averageCost, 10) : 0, // 将平均消费转换为浮点数
                    businessStatus: item.businessStatus ? 0 : 1, // 将营业状态转换为整数
                    rating: item.rating ? parseInt(item.rating * 100) : 0, // 将评分转换为浮点数
                    businessHours: item.businessHours || "",
                    address: item.address || "",
                    businessDistrict: item.businessDistrict,
                    merchantImage: item.merchantImage,
                    mainCategory: item.mainCategory,
                    middleCategory: item.middleCategory,
                    middleCategoryId: parseInt(item.middleCategoryId, 10), // 将二级分类id转换为整数
                    subCategory: item.subCategory || "",
                    brand: item.brand || "",
                    phone: item.phone + "" || "",
                    collectionTime: item.collectionTime || "",
                    createTime: item.createTime ? moment((item.createTime - (25567 + 2)) * 24 * 60 * 60 * 1000).utc().format('YYYY-MM-DD HH:MM:SS') : moment().format('YYYY-MM-DD HH:mm:ss'),
                    recommendedDishes: item.recommendedDishes,
                    smallRating: item.smallRating || "",
                };
            });
        // transformedData.length = 1;
        fs.writeFileSync(foodFilePath, JSON.stringify(foodData, null, 4), 'utf8');
        console.log(transformedData[0]);
        await this.mongodbServer.insertMany('store', transformedData); // 插入转换后的数据
    }

    /**
     * 插入食物数据
     */
    async insertFoodData() {
        const foodFilePath = path.join(__dirname, '../../data/food.json');
        if (!fs.existsSync(foodFilePath)) {
            console.log('food.json 文件不存在');
            return;
        }

        const foodData = JSON.parse(fs.readFileSync(foodFilePath, 'utf8'));
        const foodCollection = this.mongodbServer.collection('food');
        const newFoodData = [];

        for (const [name, info] of Object.entries(foodData)) {
            const existingFood = await foodCollection.findOne({ name });
            if (existingFood) {
                console.log(`食物 ${name} 已存在，跳过插入`);
                continue;
            }
            newFoodData.push(info);
        }

        if (newFoodData.length > 0) {
            await this.mongodbServer.insertMany('food', newFoodData);
            console.log(`插入了 ${newFoodData.length} 条新的食物数据`);
        } else {
            console.log('没有新的食物数据需要插入');
        }
    }
}

module.exports = MongodbDataInit;